package com.ynunicom.dc.dingdingcontractapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ynunicom.dc.dingdingcontractapp.dto.exception.TokenNullException;
import com.ynunicom.dc.dingdingcontractapp.service.GetAccessTokenService;
import com.ynunicom.dc.dingdingcontractapp.utils.AppInfoUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: jinye.Bai
 * @date: 2020/5/22 17:54
 */
@Service
public class GetAccessTokenServiceImpl implements GetAccessTokenService {

    @Resource
    RestTemplate restTemplate;

    static final String TOKEN_URL = "https://oapi.dingtalk.com/gettoken?appkey={appkey}&appsecret={appsecret}";

    @Resource
    AppInfoUtil appInfoUtil;

    @Override
    public JSONObject get() throws TokenNullException {
        Map<String,String> urlVar = new HashMap<>();
        urlVar.put("appkey",appInfoUtil.getAppKey());
        urlVar.put("appsecret",appInfoUtil.getAppSecret());
        JSONObject res = restTemplate.getForObject(TOKEN_URL,JSONObject.class,urlVar);
        if(res.isEmpty()){
            throw new TokenNullException("token交换出错");
        }
        return res;
    }
}
